<template>
  <div class="user-regis-card-wrapper">
    <i
      class="back-to-login iconfont icon-arrow-left-bold"
      @click="$emit('toLog')"
    ></i>

    <i class="iconfont icon-cancel" @click="$emit('exit')"></i>

    <h2>注册</h2>

    <ul class="input-info-list">
      <li v-for="(item, idx) in infos" :key="idx">
        <component
          :is="idx === 2 || idx === 3 ? 'PasswordInput' : 'BaseInput'"
          :placeholder="item.placeholder"
          :value="(inputs as any)[idx]"
          @change="renewInput($event.target, item.key)"
          class="info-input"
        />
        <i class="iconfont icon-warning signal" v-show="ifError[idx].sign"></i>
        <p
          class="sig-message"
          v-show="ifError[idx].sign && ifError[idx].message"
        >
          {{ ifError[idx].message }}
        </p>
      </li>
    </ul>

    <div class="verification">
      <base-input
        class="veri-input"
        placeholder="请输入验证码"
        value=""
        @change="renewInput($event.target as any, 'verification')"
      ></base-input>
      <img
        src=""
        alt=""
        ref="veriImg"
        title="点击更换验证码"
        @click="loadVeriImg"
      />
    </div>

    <button class="regis-button" @click="register" ref="registerBtn">
      Register
    </button>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, Ref } from 'vue'
import BaseInput from '../utils/Input/BaseInput.vue'
import PasswordInput from '../utils/Input/PasswordInput.vue'
import { post, get } from '@/utils/request'
import { show } from '@/utils/popup'

let inputs = reactive({
  email: '',
  username: '',
  userpwd: '',
  userpwdConfirm: '',
  verification: '',
})

let infos = reactive([
  {
    key: 'email',
    placeholder: '请输入您的邮箱',
  },
  {
    key: 'username',
    placeholder: '请输入您的用户名',
  },
  {
    key: 'userpwd',
    placeholder: '请输入密码',
  },
  {
    key: 'userpwdConfirm',
    placeholder: '确认密码',
  },
])

let ifError = reactive(
  Array.from(new Array(5), () => ({
    sign: false,
    message: '',
  }))
)

let ifShowPwd = ref(false)
let ifShowPwdCon = ref(false)

function checkEmail(email: string) {
  if (
    !/^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/.test(
      email
    )
  ) {
    ifError[0].sign = true
    ifError[0].message = '邮箱格式不正确'
    return true
  } else {
    post('register/check/email', { email })
      .then((res) => {
        ifError[0].sign = false
        ifError[0].message = res.msg
      })
      .catch((res) => {
        ifError[0].sign = true
        ifError[1].message = res.msg
      })
  }
}

function checkUsername(username: string) {
  if (username.length < 6 || username.length > 18) {
    ifError[1].sign = true
    ifError[1].message = '用户名长度必须为6-18位'
    return true
  } else if (/[^a-zA-Z0-9-_]/.test(username)) {
    ifError[1].sign = true
    ifError[1].message = '用户名只能包含字母，数字，-(连字符)和_(下划线)'
    return true
  } else {
    post('register/check/username', { username })
      .then((res) => {
        ifError[1].sign = false
        ifError[1].message = res.msg
      })
      .catch((res) => {
        ifError[1].sign = true
        ifError[1].message = res.msg
      })
  }
}

function checkPassword(password: string) {
  if (!(/[a-zA-Z]/.test(password) && /[0-9]/.test(password))) {
    ifError[2].sign = true
    ifError[2].message = '密码至少包含一个字母，一个数字'
    return true
  } else {
    ifError[2].sign = false
    return false
  }
}

function checkPasswordConfirm(p1: string, p2: string) {
  if (p1 !== p2) {
    ifError[3].sign = ifError[2].sign = true
    ifError[2].message = ''
    ifError[3].message = '两次输入密码不一致'
    return true
  } else {
    ifError[3].sign = ifError[4].sign = false
    return false
  }
}

function checkVerification(verification: string) {
  post('register/verify/code', {
    verification,
  })
    .then((res) => {
      ifError[4].sign = false
    })
    .catch((res) => {
      ifError[4].sign = true
      ifError[4].message = res.msg
      loadVeriImg()
    })
}

function renewInput(el: HTMLInputElement, key: string) {
  ;(inputs as any)[key] = el.value
  console.log('register card inputs: ', inputs)
  checkFormat(key)
}

let veriImg: Ref<HTMLImageElement | null> = ref(null)

function loadVeriImg() {
  get(
    'register/generate/code?random=' + Math.random(),
    {},
    {
      responseType: 'blob',
    }
  )
    .then((res) => {
      const reader = new FileReader()
      reader.onload = () => {
        let dom = veriImg.value as HTMLImageElement
        dom.src = reader.result as string
      }
      reader.readAsDataURL(res.data as any)
    })
    .catch((error) => {
      show('注册验证码获取失败')
    })
}

function register() {
  if (ifError.filter((e) => e.sign).length) {
    show('请填写正确的注册信息')
    return
  }
  // TODO: register
  // $store.commit('register', {
  //   infos: JSON.parse(JSON.stringify(inputs)),
  //   callback: (success) => {
  //     success && $emit('exit')
  //   },
  // })
  // $refs.registerBtn.disabled = true
}

function checkFormat(key: string) {
  switch (key) {
    case 'email':
      checkEmail(inputs.email)
      break
    case 'username':
      checkUsername(inputs.username)
      break
    case 'userpwd':
      !checkPasswordConfirm(inputs.userpwd, inputs.userpwdConfirm) &&
        checkPassword(inputs.userpwd)
      break
    case 'userpwdConfirm':
      !checkPasswordConfirm(inputs.userpwd, inputs.userpwdConfirm) &&
        checkPassword(inputs.userpwd)
      break
    case 'verification':
      checkVerification(inputs.verification)
      break
  }
}
</script>

<style scoped lang="scss">
$w: var(--userRegisCardWidth);
$fs: calc(var(--userRegisCardWidth) * 0.05);
$ifs: calc($fs * 0.8);
$iw: calc($w * 0.7);

.user-regis-card-wrapper {
  box-sizing: border-box;
  position: relative;
  width: $w;
  padding: calc($w * 0.1) calc(($w - $iw) / 2);
  background-color: white;
  border-radius: calc($w * 0.02);
  text-align: center;

  .icon-cancel {
    right: 0;

    &:hover {
      transform: rotate(180deg);
    }
  }

  .back-to-login {
    left: 0;

    &:hover {
      color: var(--darkBlue);
    }
  }

  .icon-cancel,
  .back-to-login {
    --a: 3vw;
    position: absolute;
    top: 0;
    display: block;
    width: var(--a);
    height: var(--a);
    line-height: var(--a);
    text-align: center;
    font-size: 1.2vw;
    font-weight: bold;
    color: var(--black);
    transition: 0.5s;

    &:hover {
      cursor: pointer;
    }
  }

  h2 {
    font-size: calc($fs * 1.5);
    color: var(--blue);
    line-height: 2;
  }

  .input-info-list {
    width: $iw;

    li {
      position: relative;
      margin-bottom: calc($w * 0.07);
      width: $iw;
      font-size: $fs;

      .info-input {
        --baseInputWidth: $iw;
        --baseInputHeight: calc($fs * 2);
        --baseInputFontsize: $ifs;
        --passwordInputWidth: $iw;
        --passwordInputHeight: calc($fs * 2);
        --passwordInputFontsize: $ifs;
      }

      .signal {
        position: absolute;
        left: 105%;
        top: 0;
        text-align: center;
        font-size: calc($fs * 1.3);
        color: var(--red);
      }

      .sig-message {
        margin-top: calc($fs * 0.4);
        line-height: $fs;
        margin-bottom: calc(-0.7 * $fs);
        padding: 0 calc($fs / 2);
        text-align: left;
        font-size: calc($fs * 0.2);
        color: var(--red);
      }
    }
  }

  .verification {
    margin-bottom: $fs;
    width: $iw;
    height: calc($fs * 2);
    display: flex;
    justify-content: space-between;
    align-items: center;

    .veri-input {
      --baseInputWidth: calc($iw / 2);
      --baseInputHeight: calc($fs * 2);
      --baseInputFontsize: $ifs;
    }

    img {
      width: 40%;
      height: 100%;
    }
  }

  .regis-button {
    width: $iw;
    line-height: 2;
    font-size: calc($fs * 1.2);
    color: white;
    font-weight: bold;
    border-radius: 1.5vw;
    background-image: linear-gradient(-200deg, #fac0e7, #91baff);
  }

  .register-entry {
    margin: calc($fs * 0.5) 0;
    font-size: calc($fs * 0.5);

    span {
      color: var(--blue);

      &:hover {
        cursor: pointer;
      }
    }
  }
}
</style>
